package com.arges.web.common;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * spring上下文工具类
 * 
 * @author arges
 *
 */
public class SpringContextUtils implements ApplicationContextAware
{

	private static String defaultContextPath = "classpath:applicationContext.xml";

	protected static ApplicationContext context;

	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException
	{
		SpringContextUtils.context = applicationContext;
	}

	/**
	 * 获取spring上下文
	 * 
	 * @return
	 */
	public static ApplicationContext getContext()
	{
		return context;
	}

	/**
	 * 获取spring上下文中的bean
	 * 
	 * @param <T> 注册bean的类型
	 * @param beanName 注册bean的名称
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T> T getBean(String beanName)
	{
		if (context == null)
		{
			initContext();
		}
		return (T) context.getBean(beanName);
	}

	/**
	 * 
	 * initContext:(这里描述这个方法的作用、使用方法、注意事项)
	 * 
	 * @throws
	 * @since Ver 1.1
	 */
	public static void initContext()
	{
		context = new ClassPathXmlApplicationContext(defaultContextPath);
	}

}
